package com.szcinda.service.dto.log;

import com.szcinda.repository.ExportCount;
import com.szcinda.repository.ExportCountRepository;
import com.szcinda.service.SnowFlakeFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class ExportCountServiceImpl implements ExportCountService {

    private final ExportCountRepository exportCountRepository;
    private final SnowFlakeFactory snowFlakeFactory;

    public ExportCountServiceImpl(ExportCountRepository exportCountRepository) {
        this.exportCountRepository = exportCountRepository;
        this.snowFlakeFactory = SnowFlakeFactory.getInstance();
    }

    @Override
    public int getNextNumber(String yearMonth, String type) {
        ExportCount byYearMonthAndType = exportCountRepository.findByYearAnMonthAndType(yearMonth, type);
        if (byYearMonthAndType == null) {
            byYearMonthAndType = new ExportCount();
            byYearMonthAndType.setId(snowFlakeFactory.nextId("EC"));
            byYearMonthAndType.setYearAnMonth(yearMonth);
            byYearMonthAndType.setType(type);
            byYearMonthAndType.setCount(1);
        } else {
            byYearMonthAndType.setCount(byYearMonthAndType.getCount() + 1);
        }
        exportCountRepository.save(byYearMonthAndType);
        return byYearMonthAndType.getCount();
    }
}
